var QQMapWX = require('../../libs/qqmap-wx-jssdk');
import mpImageCompress from 'mp-image-compress'
var qqmapsdk = new QQMapWX({
  key: 'H75BZ-N4JKH-2YFD2-WM3WA-5ALJO-7OBJN' //在这里输入你在腾讯位置服务平台申请的KEY
});
var timer;

const mybehavior = require("../../behaviors/requests")
Page({
  behaviors: [mybehavior],
  data: {
    fs_upload_url: "",
    device: 'back',
    flash: '',
    date: "",
    address: "",
    addressName: "",
    cameraWidth: 0,
    cameraHeight: 0,
    w: 0,
    h: 0,
    uploader: [],
    tempImagePath_show: true,
    deletable_flag: false,
    img_src: "",
    send_img: {},
    image_width: "",
    image_height: "",

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    const systemInfo = wx.getSystemInfoSync();
    const screenWidth = systemInfo.screenWidth;
    const screenHeight = systemInfo.screenHeight;
    const statusBarHeight = systemInfo.statusBarHeight;
    const menuButtonInfo = wx.getMenuButtonBoundingClientRect();
    const cameraWidth = screenWidth;
    const cameraHeight = screenHeight - statusBarHeight - menuButtonInfo.height - (menuButtonInfo.top -
      systemInfo.statusBarHeight) * 2 - 90;

    console.log(systemInfo)
    this.setData({
      cameraWidth: cameraWidth,
      cameraHeight: cameraHeight,
      image_width: cameraWidth * 0.6,
      image_height: cameraHeight * 0.6,
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.getTime()
    this.getLocation()
    let self = this
    const eventChannel = this.getOpenerEventChannel()
    // 监听acceptDataFromOpenerPage事件，获取上一页面通过eventChannel传送到当前页面的数据
    eventChannel.on('acceptDataFromOpenerPage', function (data) {
      self.setData({
        fs_upload_url: data
      })
    })
  },
  /**
   * 获取当前时间
   */
  getTime() {
    timer = setInterval(() => {
      let timeData = this.formatNowTime()
      this.setData({
        date: timeData,
      })
    }, 1000)
  },

  /**
   * 获取地址信息
   */
  getLocation() {

  },
  /**
   * 拍摄事件
   */
  takePhoto() {
    const ctx = wx.createCameraContext()
    ctx.takePhoto({
      quality: 'normal',
      success: async (res) => {
        console.log(res)
        this.setData({
          w: res.width,
          h: res.height,
          tempImagePath: res.tempImagePath
        })
        // 先图片内容安全检测
        // let checkResult = await this.checkImage(imageUrl)
        // if(checkResult==0){}

        let addWatermark = await this.addWatermark(res.tempImagePath)
        // let upload = [{
        // 	url: addWatermark,
        // 	isImage: true,

        // }]

        // this.myUploadFile(addWatermark)

        // wx.previewImage({
        // 	urls: [addWatermark],
        // })
        this.setData({
          tempImagePath_show: false,
          img_src: addWatermark
        })
      }
    })
  },
  preViewImg(e) {
    console.log(e.target.dataset.url);
    let lists = []
    lists.push(e.target.dataset.url)

    wx.previewImage({
      current: e.target.dataset.url,
      urls: lists,
    })
  },
  UploadFile() {
    wx.showLoading({
      title: '处理中...',
    })
    let file_src = this.data.img_src
    let self = this
    wx.uploadFile({
      url: self.data.fs_upload_url + '/fs_upload',
      filePath: file_src,
      name: 'file',
      formData: {},
      success(res) {
        const result = JSON.parse(res.data);
        console.log(result);
        if (result.code == 20000) {
          let obj =
          {
            url: self.data.fs_upload_url + '/fs_download?file_id=' + result.data.file_id,
            isImage: true,
            file_id: result.data.file_id
          }
          let arr = []
          arr.push(obj)
          self.setData({
            uploader: arr
          })
          let pages = getCurrentPages(); //获取当前页面pages里的所有信息。
          let prevPage = pages[pages.length - 2]; //prevPage 是获取上一个页面的js里面的pages的所有信息。 -2 是上一个页面，-3是上上个页面以此类推。
          prevPage.setData({  // 将我们想要传递的参数在这里直接setData。上个页面就会执行这里的操作。
            uploader: arr,
            img_src: result.data.file_id
          })
          //上一个页面内执行setData操作，将我们想要的信息保存住。当我们返回去的时候，页面已经处理完毕。
          //最后就是返回上一个页面。
          setTimeout(() => {
            wx.hideLoading()
            wx.navigateBack({
              delta: 1  // 返回上一级页面。
            })
          }, 600)
        } else {
          wx.showToast({
            title: result.msg,
            icon: 'none'
          })
        }
      },
      fail(err) {
        wx.showToast({
          title: err.msg,
          icon: 'none'
        })
      }
    })

  },
  addWatermark(imageUrl) {
    console.log(imageUrl)
    return new Promise((resolve, reject) => {
      wx.showLoading({
        title: '图片生成中...',
      })
      let self = this
      wx.getImageInfo({
        src: imageUrl,
        success(res) {
          console.log(res)
          var width = res.width, height = res.height;
          self.setData({//设定画布的宽高
            w: width,
            h: height
          })
          //获取当前时间
          let roleNameInfo = '拍摄时间：' + self.formatNowTime()
          let address = self.data.address
          //创建canvas
          const ctx = wx.createCanvasContext('firstCanvas');
          ctx.drawImage(res.path, 0, 0, width, height); //先画出图片
          //将声明的时间放入canvas

          ctx.setFontSize(60) //注意：设置文字大小必须放在填充文字之前，否则不生效
          ctx.setFillStyle('#ffffff');
          ctx.fillText(roleNameInfo, 80, height - 100);
          ctx.fillText(address, 80, height - 20);
          ctx.fillText('拍摄人：' + wx.getStorageSync('name'), 80, height - 180);

          ctx.draw(false, function () {
            setTimeout(function () {
              //绘画完成回调
              //生成图片
              wx.canvasToTempFilePath({
                quality: 1,
                fileType: 'jpg',
                canvasId: 'firstCanvas',
                async success(ress) {
                  wx.hideLoading()
                  const imgRes = await mpImageCompress.set(ress.tempFilePath, 500)

                  resolve(imgRes.filePath);
                  // console.log(ress.tempFilePath);//ress.tempFilePath就是带有水印的图片路径
                }, fail() {
                  wx.hideLoading()
                  reject(new Error('转换为图片失败'));
                }
              })
            }, 600)

          })
        }
      })
    });
  },
  reset() {
    this.setData({
      tempImagePath_show: true,
      img_src: '',
      send_img: {}
    })
  },
  submit() {
    wx.showToast({
      title: '确定使用该图片',
      icon: 'none'
    })
  },
  /**



  /**
   * 切换摄像头
   */
  setDevice() {
    this.setData({
      device: this.data.device == 'back' ? 'front' : 'back'
    })
    let text = this.data.device == 'back' ? '后置' : "前置";
    wx.showToast({
      title: "摄像头" + text
    })
  },

  /**
   * 闪光灯开关
   */
  setFlash() {
    this.setData({
      flash: this.data.flash == 'torch' ? 'off' : 'torch'
    })
  },



  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    clearInterval(timer)

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  onShareTimeline() {

  }
})